<?php
namespace app\common\model;
use think\Model;
use think\Db;
use fast\Cols;
use fast\Random;
use fast\Date;

class Column extends Model
{
    // 表名
    protected $name = 'column';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $pk = 'itemid';

    // 追加属性
    protected $append = [];

    public static function init(){
        self::event('after_insert', function ($row) {
            if(isset($row['iscache'])){
                model('Module')->where('itemid',$row['moduleid'])->update(['iscache'=>1]);
            }
            if($row['columnenname']=='catid'){
                if($row['optionform']=='select4'){
                    //创建关系表
                    $database = config('database.database');
                    $prefix = config('database.prefix');
                    $table = $prefix.$row['cname'].'_category';

                    $strsql = 'CREATE TABLE `'.$table.'` (';
                    $strsql .= '`'.$row['cname'].'id` bigint(20) NOT NULL DEFAULT \'0\' COMMENT \'\',';
                    $strsql .= '`catid` int(10) NOT NULL DEFAULT \'0\' COMMENT \'\',';
                    $strsql .= 'UNIQUE KEY `'.$row['cname'].'_catid` (`'.$row['cname'].'id`,`catid`),';
                    $strsql .= 'KEY `'.$row['cname'].'_id` (`'.$row['cname'].'id`),';
                    $strsql .= 'KEY `cat_id` (`'.$row['rname'].'catid`))';
                    $strsql .= ' ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'\';';
                    db()->execute('DROP TABLE IF EXISTS `'.$table.'`;');
                    db()->execute($strsql);
                    $string = '<?php'."\n";
                    $string .= 'namespace app\common\model;'."\n";
                    $string .= 'use think\Model;'."\n";
                    $string .= 'use fast\Cols;'."\n";
                    $string .= 'class '.ucfirst($row['cname']).'Category extends Model'."\n";
                    $string .= '{'."\n";
                    $string .= "\t\t".'public static function init(){'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_insert\', function($row){});'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_update\', function($row){});'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_delete\', function($row){});'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function exists($'.$row['cname'].'id=0,$catid=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['cname'].'id\'] = array(\'eq\',$'.$row['cname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$con[\'catid\'] = array(\'eq\',$catid);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";  
                    $string .= "\t\t\t\t".'return count($list)>0?1:0;'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function get'.ucfirst($row['cname']).'ByCategory($catid = 0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\'catid\'] = array(\'eq\',$catid);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";
                    $string .= "\t\t\t\t".'return $list;'."\n";
                    $string .= "\t\t".'}'."\n";
                    /*
                    $string .= "\t\t".'public function get'.ucfirst($row['rname']).'By'.ucfirst($row['cname']).'($'.$row['cname'].'id=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['cname'].'id\'] = array(\'eq\',$'.$row['cname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";
                    $string .= "\t\t\t\t".'return $list;'."\n";
                    $string .= "\t\t".'}'."\n";
                    */
                    $string .= '}'."\n";
                    $string .= '?>'."\n";
                    $filenamemodel = COMMON_PATH.DS.'model'.DS.ucfirst($row['cname']).'Category.php';
            
                    $result = file_put_contents($filenamemodel, $string);
                    if(@$fpmodel = fopen($filenamemodel, 'wb')) {
                        flock($fpmodel, LOCK_EX);
                        $len = fwrite($fpmodel, $string);
                        flock($fpmodel, LOCK_UN);
                        fclose($fpmodel);
                    }
                }
                $params = array();
                $params['itemid'] = str_replace('-','',Random::uuid());
                $params['columnname'] = '类别名称';
                $params['columnenname'] = 'categoryname';
                $params['columntype'] = 'varcharshort';
                $params['columncheck'] = '';
                $params['cname'] = $row['cname'];
                $params['moduleid'] = $row['moduleid'];
                $params['isintable'] = 0;
                $params['isshowlist'] = 1;
                $params['isshowadd'] = 0;
                $params['isshowedit'] = 0;
                $params['isshowwindow'] = 0;
                $params['isshowsearch'] = 0;
                $params['isoption'] = 0;
                $params['optionform'] = '';
                $params['options'] = '';
                $params['default'] = '';
                $params['listorder'] = 278;
                $params['intro'] = '类别名称';
                Db::name('column')->data($params)->insert();
            
                $params['itemid'] = str_replace('-','',Random::uuid());
                $params['columnname'] = '类别自定义名称';
                $params['columnenname'] = 'categorydiyname';
                $params['columntype'] = 'varcharshort';
                $params['columncheck'] = '';
                $params['cname'] = $row['cname'];
                $params['moduleid'] = $row['moduleid'];
                $params['isintable'] = 0;
                $params['isshowlist'] = 0;
                $params['isshowadd'] = 0;
                $params['isshowedit'] = 0;
                $params['isshowwindow'] = 0;
                $params['isshowsearch'] = 0;
                $params['isoption'] = 0;
                $params['optionform'] = '';
                $params['options'] = '';
                $params['default'] = '';
                $params['listorder'] = 279;
                $params['intro'] = '类别自定义名称';
                Db::name('column')->data($params)->insert();    
                
            }
            if(isset($row['relate'])&&isset($row['relatecolumn'])&&isset($row['rname'])){
                if(($row['relate']==2||$row['relate']==1)&&$row['relatecolumn']&&$row['rname']){
                    $arr = array();
                    $arr = explode(',', $row['relatecolumn']);
                    for ($i=0; $i < count($arr); $i++) { 
                        if($i<2){
                            $params = array();
                            $itemmodule = model('Module')->get(['enname'=>$row['rname']]);
                            $wherearry = array();
                            $wherearry['moduleid'] = $itemmodule['itemid'];
                            $wherearry['columnenname'] = $arr[$i];
                            $itemcolumn = model('Column')->where($wherearry)->find();
                            
                            $params['itemid'] = str_replace('-','',Random::uuid());
                            $params['columnname'] = $itemmodule['name'].$itemcolumn['columnname'];
                            $params['columnenname'] = $itemmodule['enname'].$itemcolumn['columnenname'];
                            $params['columntype'] = 'varcharshort';
                            $params['columncheck'] = '';
                            $params['cname'] = $row['cname'];
                            $params['moduleid'] = $row['moduleid'];
                            $params['isintable'] = 0;
                            $params['isshowlist'] = 1;
                            $params['isshowadd'] = 0;
                            $params['isshowedit'] = 0;
                            $params['isshowwindow'] = 0;
                            $params['isshowsearch'] = 0;
                            $params['isoption'] = 0;
                            $params['optionform'] = '';
                            $params['options'] = '';
                            $params['default'] = '';
                            $params['listorder'] = 323+$i;
                            $params['intro'] = $itemmodule['name'].$itemcolumn['columnname'];
                            Db::name('column')->data($params)->insert();
                        }
                    }
                                
                }
                if($row['relate']==3){
                    $params = array();
                    $params['isintable'] = 0;
                    $params['isshowlist'] = 0;
                    $params['isshowadd'] = 1;
                    $params['isshowedit'] = 1;
                    $params['isshowwindow'] = 0;
                    $params['isshowsearch'] = 0;
                    $params['isoption'] = 0;
                    $params['isimport'] = 0;
                    $params['iscache'] = 0;
                    Db::name('column')->where('itemid',$row['itemid'])->update($params);

                    //创建关系表
                    $database = config('database.database');
                    $prefix = config('database.prefix');
                    $table = $prefix.$row['cname'].'_'.$row['rname'];

                    $strsql = 'CREATE TABLE `'.$table.'` (';
                    $strsql .= '`'.$row['cname'].'id` bigint(20) NOT NULL DEFAULT \'0\' COMMENT \'\',';
                    $strsql .= '`'.$row['rname'].'id` bigint(20) NOT NULL DEFAULT \'0\' COMMENT \'\',';
                    $strsql .= 'UNIQUE KEY `'.$row['cname'].'_'.$row['rname'].'_id` (`'.$row['cname'].'id`,`'.$row['rname'].'id`),';
                    $strsql .= 'KEY `'.$row['cname'].'_id` (`'.$row['cname'].'id`),';
                    $strsql .= 'KEY `'.$row['rname'].'_id` (`'.$row['rname'].'id`))';
                    $strsql .= ' ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'\';';
                    db()->execute('DROP TABLE IF EXISTS `'.$table.'`;');
                    db()->execute($strsql);

                    $string = '<?php'."\n";
                    $string .= 'namespace app\common\model;'."\n";
                    $string .= 'use think\Model;'."\n";
                    $string .= 'use fast\Cols;'."\n";
                    $string .= 'class '.ucfirst($row['cname']).ucfirst($row['rname']).' extends Model'."\n";
                    $string .= '{'."\n";
                    $string .= "\t\t".'public static function init(){'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_insert\', function($row){});'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_update\', function($row){});'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_delete\', function($row){});'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function exists($'.$row['cname'].'id=0,$'.$row['rname'].'id=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['cname'].'id\'] = array(\'eq\',$'.$row['cname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['rname'].'id\'] = array(\'eq\',$'.$row['rname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";  
                    $string .= "\t\t\t\t".'return count($list>0)?1:0;'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function get'.ucfirst($row['cname']).'By'.ucfirst($row['rname']).'($'.$row['rname'].'id=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['rname'].'id\'] = array(\'eq\',$'.$row['rname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";
                    $string .= "\t\t\t\t".'return $list;'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function get'.ucfirst($row['rname']).'By'.ucfirst($row['cname']).'($'.$row['cname'].'id=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['cname'].'id\'] = array(\'eq\',$'.$row['cname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";
                    $string .= "\t\t\t\t".'return $list;'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= '}'."\n";
                    $string .= '?>'."\n";
                    $filenamemodel = COMMON_PATH.DS.'model'.DS.ucfirst($row['cname']).ucfirst($row['rname']).'.php';
            
                    $result = file_put_contents($filenamemodel, $string);
                    if(@$fpmodel = fopen($filenamemodel, 'wb')) {
                        flock($fpmodel, LOCK_EX);
                        $len = fwrite($fpmodel, $string);
                        flock($fpmodel, LOCK_UN);
                        fclose($fpmodel);
                    }
                }
            }
        });
        self::event('after_update', function ($row) {
            if(isset($row['iscache'])){
                model('Module')->where('itemid',$row['moduleid'])->update(['iscache'=>1]);
            }
            if($row['columnenname']=='catid'){
                if($row['optionform']=='select4'){
                    //创建关系表
                    $database = config('database.database');
                    $prefix = config('database.prefix');
                    $table = $prefix.$row['cname'].'_category';

                    $strsql = 'CREATE TABLE `'.$table.'` (';
                    $strsql .= '`'.$row['cname'].'id` bigint(20) NOT NULL DEFAULT \'0\' COMMENT \'\',';
                    $strsql .= '`catid` int(10) NOT NULL DEFAULT \'0\' COMMENT \'\',';
                    $strsql .= 'UNIQUE KEY `'.$row['cname'].'_catid` (`'.$row['cname'].'id`,`catid`),';
                    $strsql .= 'KEY `'.$row['cname'].'_id` (`'.$row['cname'].'id`),';
                    $strsql .= 'KEY `cat_id` (`'.$row['rname'].'catid`))';
                    $strsql .= ' ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'\';';
                    db()->execute('DROP TABLE IF EXISTS `'.$table.'`;');
                    db()->execute($strsql);
                    $string = '<?php'."\n";
                    $string .= 'namespace app\common\model;'."\n";
                    $string .= 'use think\Model;'."\n";
                    $string .= 'use fast\Cols;'."\n";
                    $string .= 'class '.ucfirst($row['cname']).'Category extends Model'."\n";
                    $string .= '{'."\n";
                    $string .= "\t\t".'public static function init(){'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_insert\', function($row){});'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_update\', function($row){});'."\n";
                    $string .= "\t\t\t\t".'self::event(\'after_delete\', function($row){});'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function exists($'.$row['cname'].'id=0,$catid=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['cname'].'id\'] = array(\'eq\',$'.$row['cname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$con[\'catid\'] = array(\'eq\',$catid);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";  
                    $string .= "\t\t\t\t".'return count($list)>0?1:0;'."\n";
                    $string .= "\t\t".'}'."\n";
                    $string .= "\t\t".'public function get'.ucfirst($row['cname']).'ByCategory($catid = 0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\'catid\'] = array(\'eq\',$catid);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";
                    $string .= "\t\t\t\t".'return $list;'."\n";
                    $string .= "\t\t".'}'."\n";
                    /*
                    $string .= "\t\t".'public function get'.ucfirst($row['rname']).'By'.ucfirst($row['cname']).'($'.$row['cname'].'id=0){'."\n";
                    $string .= "\t\t\t\t".'$con = array();'."\n";
                    $string .= "\t\t\t\t".'$con[\''.$row['cname'].'id\'] = array(\'eq\',$'.$row['cname'].'id);'."\n";
                    $string .= "\t\t\t\t".'$list = $this->where($con)->select();'."\n";
                    $string .= "\t\t\t\t".'return $list;'."\n";
                    $string .= "\t\t".'}'."\n";
                    */
                    $string .= '}'."\n";
                    $string .= '?>'."\n";
                    $filenamemodel = COMMON_PATH.DS.'model'.DS.ucfirst($row['cname']).'Category.php';
            
                    $result = file_put_contents($filenamemodel, $string);
                    if(@$fpmodel = fopen($filenamemodel, 'wb')) {
                        flock($fpmodel, LOCK_EX);
                        $len = fwrite($fpmodel, $string);
                        flock($fpmodel, LOCK_UN);
                        fclose($fpmodel);
                    }
                }
                $arr = model('Column')->getColumnsByModel($row['cname'],$row['moduleid'],'categoryname');
                if(count($arr)==0){
                    $params = array();
                    $params['itemid'] = str_replace('-','',Random::uuid());
                    $params['columnname'] = '类别名称';
                    $params['columnenname'] = 'categoryname';
                    $params['columntype'] = 'varcharshort';
                    $params['columncheck'] = '';
                    $params['cname'] = $row['cname'];
                    $params['moduleid'] = $row['moduleid'];
                    $params['isintable'] = 0;
                    $params['isshowlist'] = 1;
                    $params['isshowadd'] = 0;
                    $params['isshowedit'] = 0;
                    $params['isshowwindow'] = 0;
                    $params['isshowsearch'] = 0;
                    $params['isoption'] = 0;
                    $params['optionform'] = '';
                    $params['options'] = '';
                    $params['default'] = '';
                    $params['listorder'] = 279;
                    $params['intro'] = '类别名称';
                    Db::name('column')->data($params)->insert();
                }
                $arr = model('Column')->getColumnsByModel($row['cname'],$row['moduleid'],'categorydiyname');
                if(count($arr)==0){
                    $params['itemid'] = str_replace('-','',Random::uuid());
                    $params['columnname'] = '类别名称';
                    $params['columnenname'] = 'categorydiyname';
                    $params['columntype'] = 'varcharshort';
                    $params['columncheck'] = '';
                    $params['cname'] = $row['cname'];
                    $params['moduleid'] = $row['moduleid'];
                    $params['isintable'] = 0;
                    $params['isshowlist'] = 1;
                    $params['isshowadd'] = 0;
                    $params['isshowedit'] = 0;
                    $params['isshowwindow'] = 0;
                    $params['isshowsearch'] = 0;
                    $params['isoption'] = 0;
                    $params['optionform'] = '';
                    $params['options'] = '';
                    $params['default'] = '';
                    $params['listorder'] = 279;
                    $params['intro'] = '类别自定义名称';
                    Db::name('column')->data($params)->insert();
                }
            }
            if(isset($row['relate'])&&isset($row['relatecolumn'])&&isset($row['rname'])){
                if(($row['relate']==2||$row['relate']==1)&&$row['relatecolumn']&&$row['rname']){
                    $itemmodule = model('Module')->get(['enname'=>$row['rname']]);//取出关联模型
                    //$itemm = model('Module')->get($row['moduleid']);
                    $arr = array();
                    $arr = explode(',', $row['relatecolumn']);

                    for ($i=0; $i < count($arr); $i++) { 
                        $params = array();
                        $wherearry = array();
                        $wherearry['moduleid'] = $itemmodule['itemid'];
                        $wherearry['columnenname'] = $arr[$i];
                        $itemcolumn = model('Column')->where($wherearry)->find();
                        //判断是否存在于此模型中
                        $arrc = model('Column')->getColumnsByModel($row['cname'],$row['moduleid'],$itemmodule['enname'].$itemcolumn['columnenname']);
                        if(count($arrc)==0){
                            $params['itemid'] = str_replace('-','',Random::uuid());
                            $params['columnname'] = $itemmodule['name'].$itemcolumn['columnname'];
                            $params['columnenname'] = $itemmodule['enname'].$itemcolumn['columnenname'];
                            $params['columntype'] = 'varcharshort';
                            $params['columncheck'] = '';
                            $params['cname'] = $row['cname'];
                            $params['moduleid'] = $row['moduleid'];
                            $params['isintable'] = 0;
                            $params['isshowlist'] = 1;
                            $params['isshowadd'] = 0;
                            $params['isshowedit'] = 0;
                            $params['isshowwindow'] = 0;
                            $params['isshowsearch'] = 0;
                            $params['isoption'] = 0;
                            $params['optionform'] = '';
                            $params['options'] = '';
                            $params['default'] = '';
                            $params['listorder'] = 324;
                            $params['intro'] = $itemmodule['name'].$itemcolumn['columnname'];
                            Db::name('column')->data($params)->insert();
                        }
                    }               
                }
                if($row['relate']==3){
                    $params = array();
                    $params['isshowlist'] = 0;
                    $params['isshowadd'] = 0;
                    $params['isshowedit'] = 0;
                    $params['isshowwindow'] = 0;
                    $params['isshowsearch'] = 0;
                    $params['isoption'] = 0;
                    $params['isimport'] = 0;
                    $params['iscache'] = 0;
                    Db::name('column')->where('itemid',$row['itemid'])->update($params);
                }
            }
            
        });
    }
    public function module(){
        return $this->belongsTo('Module','moduleid','itemid')->field('id,name,enname,relate,relation');
    }
    //modelname 实体名称 
    public function getColumnsByShowwindow($modelname = ''){
        $where = array();
        $where['cname'] = $modelname;
        $where['isshowwindow'] = 1;
        $list = $this->where($where)->select();
        return $list;
    }
    //modelname 实体名称  relateid {"1":"一对一"},{"2":"多对一"},{"3":"多对多"},{"4":"一对多"}
    public function getColumnsByRelate($modelname = '',$relateid = 1){
        $where = array();
        if($modelname){
            switch($relateid){
                case 4:
                    $where['rname'] = $modelname;
                    $where['relate'] = 2;
                break;
                case 3:
                    $where['rname'] = $modelname;
                    $where['relate'] = 3;
                break;
                default:
                    $where['cname'] = $modelname;
                break;
            }
        }
        if($relateid){
            if($relateid < 3){
                $where['relate'] = $relateid;
            }
        }
        $list = $this->where($where)->select();
        return $list;
    }

    public function getColumnsByRelation($modelname = ''){
        $where['rname'] = $modelname;
        $list = $this->where($where)->select();
        return $list;
    }
    //根据模型名称或者模型编号，得到字段
    public function getColumnsByModel($name = '',$moduleid = '',$enname = ''){
        $condition = array();$list = array();
        if($name){
            $condition['cname'] = $name;
        }
        if($moduleid){
            $condition['moduleid'] = $moduleid;
        }
        if($enname){
            $condition['columnenname'] = $enname;
        }
        $listobjarr = $this->where($condition)->order('listorder')->select();
        if(!empty($listobjarr)) {
            foreach ($listobjarr as $val) {
                $list[] = $val->toArray();
            }
            if (!empty($list)) {return $list;}
            else{return array();}
        }else{
            return array();
        }
    }

}
?>
